package com.chcit.mobile.mvp.common.presenter;

import android.app.Application;
import androidx.fragment.app.Fragment;
import androidx.core.app.ComponentActivity;

import com.alibaba.fastjson.JSONObject;
import com.chcit.mobile.app.utils.SharedPreUtils;
import com.chcit.mobile.common.DataKeys;
import com.chcit.mobile.common.SPDErrorHandle;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.mvp.common.contract.LoginContract;
import com.chcit.mobile.mvp.entity.UserBean;
import com.chcit.mobile.mvp.entity.WareHose;
import com.jess.arms.base.app.ConfigKeys;
import com.jess.arms.base.app.Quick;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class LoginFragmentPresenter extends BasePresenter<LoginContract.Model, LoginContract.FragmentView> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public LoginFragmentPresenter(LoginContract.Model model, LoginContract.FragmentView rootView) {
        super(model, rootView);
    }
    /**
     * 使用 2017 Google IO 发布的 Architecture Components 中的 Lifecycles 的新特性 (此特性已被加入 Support library)
     * 使 {@code Presenter} 可以与 {@link ComponentActivity} 和 {@link Fragment} 的部分生命周期绑定
     */


    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void login(String userName, String passWord) {
       mModel.login(userName,passWord)
               .retryWhen(new RetryWithDelay(3, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
               .observeOn(AndroidSchedulers.mainThread())
               .doOnSubscribe(disposable -> {
                   mRootView.showLoading();
               })
               .doFinally(() -> {
                   mRootView.hideLoading();//隐藏下拉刷新的进度条

               })
               .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
               .subscribe(new ErrorHandleSubscriber<JSONObject>(mErrorHandler) {
                   @Override
                   public void onNext(JSONObject jsonObject) {
                       if(jsonObject.getBoolean("success")){
                           UserBean user = jsonObject.toJavaObject(UserBean.class);
                           String tocken = jsonObject.getString("chcToken");
                           Quick.withConfigure(ConfigKeys.TOKEN,tocken);
                           Quick.withConfigure(ConfigKeys.APP_SESSION_ID,jsonObject.getString("appSessionID"));
                           user.setPassword(passWord);
                           user.setUsername(userName);
                           HttpClientHelper.setUser(user);
                           SharedPreUtils.getInstance().putString(DataKeys.USERNAME.name(),userName);
                           HttpClientHelper.clearWares();
                           mModel.getWares().subscribeOn(Schedulers.io())
                                   .observeOn(AndroidSchedulers.mainThread())
                                   .subscribe(new SPDErrorHandle<List<WareHose>>(mErrorHandler) {

                                       @Override
                                       public void onNext(List<WareHose> wares) {
                                           Quick.withConfigure(DataKeys.WAREHOUSE_LIST,wares);
                                           mRootView.toHomeActivity();
                                       }

                                       @Override
                                       public void onError(Throwable t) {
                                           super.onError(t);
                                       }
                                   });

                       }else{
                           onError( new Exception(jsonObject.getString("msg")));
                       }

                   }

               });
    }


}
